<template>
  <div class="svg-icon svg-external-icon"
       v-if="isExt"
       :style="styleExternalIcon"
       v-bind="$attrs"
  >
  </div>
  <svg v-else :class="svgClass" aria-hidden="true" v-bind="$attrs">
    <!-- svg中use元素可以调用其他svg文件 <use xlink:href="#symbolId"></use> -->
    <use :xlink:href="iconName" />
  </svg>
</template>

<script lang="ts">
import { isExternal } from '@/utils/validate'
import { computed, defineComponent } from 'vue'

export default defineComponent({
  name: 'SvgIcon',
  // 组件上的$attrs不自动添加到组件根元素上 默认添加到组件根元素上
  inheritAttrs: false,
  props: {
    iconClass: {
      type: String,
      require: true
    },
    className: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    // 是否送带协议的图片链接
    const isExt = computed(() => isExternal(props.iconClass || ''))

    // 拼接成symbolId 在loader 配置中指定格式
    const iconName = computed(() => `#icon-${props.iconClass}`)
    const svgClass = computed(() => props.className ? `svg-icon ${props.className}` : 'svg-icon')

    const styleExternalIcon = computed(() => ({
      mask: `url(${props.iconClass} no-repeat 50% 50%)`,
      '-webkit-mask': `url(${props.iconClass}) no-repeat 50% 50%`
    }))

    return {
      isExt,
      iconName,
      svgClass,
      styleExternalIcon
    }
  }
})

</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>
